package com.yans.managers
{
	import com.yans.interfaces.IMouseManager;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	
	public class MouseManager extends EventDispatcher implements IMouseManager, IEventDispatcher
	{ 
		
		public function get height():int { 
			return _height;
		}
		
		public function get width():int { 
			return _width;
		}
		
		private var _stage:Stage;
		public var _width:int;
		public var _height:int;
		
		public function MouseManager(stage:Stage) {
			_stage = stage;
			_stage.addEventListener(Event.RESIZE, onResized);
			onResized(null); 
		}
		
		private var _mouseMoveRect:Rectangle;
		private var _callBack:Function;
		private var _target:Sprite;
		
		private function onResized(e:Event):void {
			_width = _stage.stageWidth;
			_height = _stage.stageHeight;
			dispatchEvent(new Event(Event.RESIZE));
		}
		
		/**
		 *	鼠标可以拖动
		 * @param display
		 * 
		 */		
		public function bindMoveable(display:Sprite, rect:Rectangle = null, callback:Function = null):void {
			_mouseMoveRect = rect; 
			if(display.hasEventListener(MouseEvent.MOUSE_DOWN)) {
				display.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			}	
			display.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			_callBack = callback;
		}
		private function onMouseDown(e:MouseEvent):void {
			var obj:Sprite = e.target as Sprite;
			obj.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			obj.startDrag(false, _mouseMoveRect);
			_target = obj;
		}
		private function onMouseUp(e:MouseEvent):void { 
			_target.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			_target.stopDrag();
			trace("#", _target.x, _target.y);
			if(null != _callBack) _callBack(_target.x, _target.y);
		}
		
	}
}